import { accessSync, mkdirSync } from 'fs'
import * as multer from 'multer'
import { join } from 'path'
import { ResponseUtil } from '../helpers/ResponseUtil'
import utils from '../helpers/utils'
import { Post } from '../metadata'
import { KoaContext } from '../server'

const storage = multer.diskStorage({
  destination: (_req: any, _file, cb) => {
    const p = join(__dirname, '../../static')
    try {
      accessSync(p)
      cb(null, p)
    } catch (error) {
      mkdirSync(p)
      cb(null, p)
    }
  },

  filename: (_req, file, cb) => {
    const { originalname } = file
    const filename = `${Date.now()}_${utils.random(0, 100, true)}_${originalname}`
    cb(null, filename)
  }
})

const IMAGE_TYPE = /^image\//
const VIDEO_TYPE = /^video\//

const upload = multer({
  storage, fileFilter: (_req, file, cb) => {
    const { mimetype } = file
    if (IMAGE_TYPE.test(mimetype) || VIDEO_TYPE.test(mimetype)) {
      return cb(null, true)
    }
    return cb(new Error('not support file type'), false)
  }
})

export default class UploadController {

  @Post('/upload')
  public async upload(ctx: KoaContext) {
    try {
      const { filename } = await this.uploadFile(ctx)
      return ResponseUtil.success({ data: { url: filename } })
    } catch (error) {
      console.error(error)
      return ResponseUtil.fail(4005, '文件上传错误')
    }
  }

  // NOTE: 这里跳过检查
  private async uploadFile(ctx: any) {
    const middleware = upload.single('file')
    return new Promise<Express.Multer.File>((resolve, reject) => {
      middleware(ctx.req, ctx.res, (err: any) => {
        err ? reject(err) : resolve(ctx.req.file)
      })
    })
  }
}
